import 'dart:math';

import 'package:al_utils/extensions/date_extension.dart';
import 'package:flutter/material.dart';

extension StringExtesnion on String? {
  bool get isEmptyOrNull => this == null || (this != null && this!.isEmpty) || (this != null && this! == 'null');

  String validate({String value = ''}) {
    if (isEmptyOrNull) {
      return value;
    } else {
      return this!;
    }
  }

  bool get isEmpty {
    return validate().isEmpty;
  }

  bool get isNotEmpty {
    return validate().isNotEmpty;
  }

  String breakWord() {
    if (this == null || isEmpty) {
      return validate();
    }
    String breakWord = '';
    for (var element in this!.runes) {
      breakWord += String.fromCharCode(element);
      breakWord += '\u200B';
    }
    return breakWord;
  }

  Size boundingTextSize(TextStyle style, {int maxLines = 2 ^ 31, double maxWidth = double.infinity}) {
    if (this == null || isEmpty) {
      return Size.zero;
    }
    final TextPainter textPainter = TextPainter(textDirection: TextDirection.ltr, text: TextSpan(text: this, style: style), maxLines: maxLines)
      ..layout(maxWidth: maxWidth);
    return textPainter.size;
  }

  formatDateTime() {
    return DateTime.parse(or()).fullFormat;
  }
}

extension StringUtil on String {

  static String random(int length) {
    final random = Random();
    const availableChars = 'AaBbCcDdEeFfGgHhIiJjKkLlMmNnOoPpQqRrSsTtUuVvWwXxYyZz1234567890';
    return List.generate(length, (index) => availableChars[random.nextInt(availableChars.length)]).join();
  }

  String removeTrailingZero() {
    if (!contains('.')) {
      return this;
    }
    var string = replaceAll(RegExp(r'0*$'), '');
    if (string.endsWith('.')) {
      string = string.substring(0, string.length - 1);
    }
    return string;
  }
}

extension OrDefault<T> on T? {
  T or({T? defaultValue}) {
    final value = this;
    if (value != null) return value;
    if (defaultValue != null) return defaultValue;
    return {int: 0, String: '', double: 0.0, Map: {}, bool: false, List: []}[T] as T;
  }
}
